package Utils

import java.io.{File, PrintWriter}

import scalikejdbc._
import scalikejdbc.config._

import scala.io.Source

/**
  * Created by hunter.coder 涛哥  
  * 2019/2/12 15:04
  * 交流qq:657270652
  * Version: 1.0
  * 更多学习资料：https://blog.csdn.net/coderblack/
  * Description:
  **/
object DictUtil {


  /**
    * 从数据库中加载 区位码和对应的经纬度到数据文件中
    */
  def loadDB2File: Unit = {
    DBs.setupAll()
    //DBs.setup('dicts)
    val snlist: List[(Int,Option[Double],Option[Double])] = DB readOnly { implicit session =>
      sql"select * from t_md_areas".map(wr => (wr.int("id"),wr.doubleOpt("bd09_lng"),wr.doubleOpt("bd09_lat")  )
      ).list().apply()}

    val pw = new PrintWriter( new File("d:/area_code.dat"))
    for (elem <- snlist) {
      val name = elem._1
      val lat = if(elem._2.isEmpty) "" else elem._2.get.toString
      val lng = if(elem._3.isEmpty) "" else elem._3.get.toString
      pw.println(s"${name},${lat},${lng}" )
    }

    pw.close()

    DBs.closeAll()
  }


  /**
    * 从数据库中加载区域数据为List
    */
  def loadArea2List:List[(Int,Option[Double],Option[Double])]={

    DBs.setupAll()
    //DBs.setup('dicts)
    val snlist: List[(Int,Option[Double],Option[Double])] = DB readOnly { implicit session =>
      sql"select * from t_md_areas".map(wr => (wr.int("id"),wr.doubleOpt("bd09_lng"),wr.doubleOpt("bd09_lat")  )
      ).list().apply()}

    snlist
  }

  /**
    * 从文件中加载区域数据为List
    */
  def loadArea2List2(areafile:String):List[(Int,Option[Double],Option[Double])]= {

    val f = Source.fromFile(areafile)
    println("成功加载本地区域代码数据文件.....")
    val snlist = new scala.collection.mutable.ListBuffer[(Int,Option[Double],Option[Double])]
    for(line <- f.getLines()){

      val fields = line.split(",")
      if(fields.size>2) {
        val code = fields(0).toInt
        val lat = if (fields(1).isEmpty) -1 else fields(1).toDouble
        val lng = if (fields(2).isEmpty) -1 else fields(2).toDouble
        snlist += ((code, Option(lat), Option(lng)))
      }
    }

    snlist.toList
  }


  /**
    * 加载app渠道数据
    * @return
    */
  def loadAppRlCh2List(chfile:String):List[String] = {
    println("成功加载本地app release渠道数据文件.....")
    val f = Source.fromFile(chfile)
    val chs: Iterator[String] = for(line <- f.getLines()) yield line
    chs.toList
  }

  /**
    * 测试
    * @param args
    */
  def main(args: Array[String]): Unit = {
    val list = loadArea2List2("")
    println(list.size)
  }

}
